//package com.ruoyi.common.utils.pay;
//
//import com.alipay.api.internal.util.file.ByteArrayOutputStream;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.fasterxml.jackson.databind.node.ObjectNode;
//import com.ruoyi.common.config.PayConfig;
//import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
//import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
//import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
//import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
//import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
//import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
//import com.wechat.pay.contrib.apache.httpclient.exception.HttpCodeException;
//import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
//import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
//import org.apache.http.client.HttpClient;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.client.utils.URIBuilder;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.util.EntityUtils;
//
//import java.io.ByteArrayInputStream;
//import java.io.FileInputStream;
//import java.io.IOException;
//import java.nio.charset.StandardCharsets;
//import java.security.GeneralSecurityException;
//import java.security.PrivateKey;
//
//public class WechatPayUtil {
//
//    static CloseableHttpClient httpClient = null;
//
//    static
//    {
//        initHttpClient();
//    }
//    /**
//     * 初始化httpClient
//     */
//    private static HttpClient initHttpClient()  {
//        // 加载商户私钥（privateKey：私钥字符串）
//        String privateKey = PayConfig.getPrivatekey();
//        String mchId = PayConfig.getMchId();
//        String mchSerialNo =PayConfig.getMchSerialNo();
//        String apiV3Key = PayConfig.getApiV3Key();
//
//        try {
//            // 加载平台证书（mchId：商户号,mchSerialNo：商户证书序列号,apiV3Key：V3密钥）
////            AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
////                    new WechatPay2Credentials(mchId, new PrivateKeySigner(mchSerialNo, merchantPrivateKey)),apiV3Key.getBytes("utf-8"));
//            PrivateKey merchantPrivateKey = getPrivateKey(2);
//
//            Verifier verifier = getVerifier(mchId,merchantPrivateKey,mchSerialNo,apiV3Key);
//
//            // 初始化httpClient
//              httpClient = WechatPayHttpClientBuilder.create()
//                    .withMerchant(mchId, mchSerialNo, merchantPrivateKey)
//                    .withValidator(new WechatPay2Validator(verifier)).build();
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return httpClient;
//    }
//
//    /**
//     * 获取平台证书
//     * @return
//     */
//    public String getCertificates(){
//
//        String bodyAsString = "";
//        try {
//            URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/certificates");
//            HttpGet httpGet = new HttpGet(uriBuilder.build());
//            httpGet.addHeader("Accept", "application/json");
//            CloseableHttpResponse response = httpClient.execute(httpGet);
//            bodyAsString = EntityUtils.toString(response.getEntity());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return  bodyAsString;
//    }
//
//    /**
//     * 获取商户私钥，
//     * @param type 1、私钥存储在文件 2、私钥为String字符串
//     * @return
//     */
//    public static PrivateKey getPrivateKey(int type){
//        PrivateKey merchantPrivateKey = null;
//        try {
//            if(type==1){
//                merchantPrivateKey = PemUtil.loadPrivateKey(
//                        new ByteArrayInputStream(PayConfig.getPrivatekey().getBytes("utf-8")));
//            }else {
//                merchantPrivateKey = PemUtil.loadPrivateKey(new FileInputStream(PayConfig.getPrivatekeyPath()));
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return merchantPrivateKey;
//    }
//
//    /**
//     * 获取证书
//     * @param merchantId
//     * @param merchantPrivateKey
//     * @param merchantSerialNumber
//     * @param apiV3Key
//     * @return
//     */
//    public static Verifier getVerifier(String merchantId,PrivateKey merchantPrivateKey,String merchantSerialNumber,String apiV3Key){
//        // 获取证书管理器实例
//        CertificatesManager certificatesManager = CertificatesManager.getInstance();
//        Verifier verifier = null;
//       // 向证书管理器增加需要自动更新平台证书的商户信息
//        try {
//            certificatesManager.putMerchant(merchantId, new WechatPay2Credentials(merchantId,
//                    new PrivateKeySigner(merchantSerialNumber, merchantPrivateKey)), apiV3Key.getBytes(StandardCharsets.UTF_8));
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (GeneralSecurityException e) {
//            e.printStackTrace();
//        } catch (HttpCodeException e) {
//            e.printStackTrace();
//        }
//        // ... 若有多个商户号，可继续调用putMerchant添加商户信息
//
//       // 从证书管理器中获取verifier
//        try {
//            verifier = certificatesManager.getVerifier(merchantId);
//        } catch (NotFoundException e) {
//            e.printStackTrace();
//        }
//
//        return verifier;
//    }
//
//    /**
//     * App下单
//     * @return
//     */
//    public static String createAppOrder(Double amount_total,String description){
//
//        String bodyAsString = "";
//        HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/app");
//        httpPost.addHeader("Accept", "application/json");
//        httpPost.addHeader("Content-type","application/json; charset=utf-8");
//
//        ByteArrayOutputStream bos = new ByteArrayOutputStream();
//        ObjectMapper objectMapper = new ObjectMapper();
//
//        ObjectNode rootNode = objectMapper.createObjectNode();
//        rootNode.put("mchid",PayConfig.getMchId())
//                .put("appid", PayConfig.getAppId())
//                .put("description", description)
//                .put("notify_url", PayConfig.getNotifyUrl())
//                .put("out_trade_no", System.currentTimeMillis()+"");
//        rootNode.putObject("amount")
//                .put("total", amount_total);
//        rootNode.putObject("payer")
//                .put("openid", PayConfig.getOpenId());
//
//        try {
//            objectMapper.writeValue(bos, rootNode);
//            httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
//            CloseableHttpResponse response = httpClient.execute(httpPost);
//            bodyAsString = EntityUtils.toString(response.getEntity());
//            System.out.println(bodyAsString);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return  bodyAsString;
//    }
//
//
//}
